//
//  ChatBarFaceViewTopViewConstomPageView.m
//  keyboard
//
//  Created by 遇水 on 16/3/25.
//  Copyright © 2016年 遇水. All rights reserved.
//

#import "ChatBarFaceViewTopViewConstomPageView.h"
#import "FaceModel.h"
#import "UIView+Extension.h"
#import "Utiles.h"
#import "ImageManager.h"

@implementation ChatBarFaceViewTopViewConstomPageView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    
    return self;
}

//这里还有点缺陷
-(void)setDataSource:(NSArray *)dataSource
{
    _dataSource = dataSource;
    
    for (NSInteger i = 0; i < dataSource.count; i ++) {
        UIButton *button = [[UIButton alloc]init];
        FaceModel *model  = dataSource[i];
        
        if (model.code) {
            [button setTitle:model.code.emoji forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:32];
        }else if(model.png){
            [button setImage:[UIImage imageNamed:model.png] forState:UIControlStateNormal];
        }else if(model.urlString){
           UIImage *image =  [[ImageManager sharedImageManager]imageWithToPath:model.urlString];
            [button setImage:image forState:UIControlStateNormal];
        }
       
        button.tag = i;
        [button setBackgroundColor:[UIColor grayColor]];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat edgeW = 5;
    NSUInteger count = self.dataSource.count;
    //一行5个 两行
    CGFloat buttonW = (self.width - 2* edgeW) / constomFaceMaxColum;
    CGFloat buttonH = (self.height - edgeW) / constomFaceMaxRows;
    
    for (NSInteger i = 0; i < count; i++) {
        UIButton *button = self.subviews[i];
        button.adjustsImageWhenHighlighted = NO;
        button.adjustsImageWhenDisabled = NO;
        
        button.x = edgeW +(i% constomFaceMaxColum) * buttonW;
        button.y = edgeW + (i / constomFaceMaxColum) * buttonH;
        button.width = buttonW;
        button.height = buttonH;
    }
}

-(void)buttonAction:(UIButton *)button
{
    //说明点击的是添加按钮
    if (button.tag == self.dataSource.count - 1) {
       [[NSNotificationCenter defaultCenter]postNotificationName:NotificationConstomAdd object:nil];
    }else
    {
    NSDictionary *userInfo  =@{Face : self.dataSource[button.tag]};
    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationConstomFace object:nil userInfo:userInfo];

    }
}


@end
